var sugarcane = {
  "version": "0.0.1"
};

// 公共变量
sugarcane['app'] = {
  "userAgent": window.navigator.userAgent,
  "ua": window.navigator.userAgent.toLocaleLowerCase(),
  "isShare": true, // 默认是分享页，通过APP的 userAgent 判断是否是分享页
  "isWeixin": false, // 默认不是微信，通过 userAgent 的 MicroMessenger 判断
  "isQQ": false, // 默认不是QQ，通过 userAgent 的 MicroMessenger 判断
  "appName": null, // App名字
  "appVersion": null, // App版本
  "appNopic": false, // 默认关闭无图模式，App端在可设置开启
  "fontSize": "medium", // 字体大小，默认正常
  "userId": null,
  "token": 'unlogin123456'
};

(function(){
  // App userAgent: app名/版本/无图模式/字体大小，如：jjrb/5.2.2/0/xx-small
  if (sugarcane['app']['ua'].indexOf('jjrb/') > -1) {
    sugarcane['app']['isShare'] = false;
    sugarcane['app']['appName'] = 'jjrb';
    var _appUA = sugarcane['app']['ua'].match(/jjrb\/([\d\.a-z\-\/]*)/i)[0].split('/');
    sugarcane['app']['appVersion'] = _appUA[1];
    if (_appUA[2] == 1) sugarcane['app']['appNopic'] = true;
    if (_appUA[3]) sugarcane['app']['fontSize'] = _appUA[3];

  } else {
    if (sugarcane['app']['ua'].indexOf('micromessenger') > -1) {
      sugarcane['app']['isWeixin'] = true;
    }else if(sugarcane['app']['ua'].indexOf('qq') > -1){
      sugarcane['app']['isQQ'] = true;
    }

  }
}());
/*
  2018-10-28 ysh 注明
  公共函数中的参数params param 都代表改函数接受多个参数 只是 params 是小花的命名： 认为有多个参数应该用复数形式 param是该套组件的原创所作
*/
// 获取地址栏参数
sugarcane['getUrlParams'] = function(){
  var urlParams = {},
    search = window.location.search.substr(1);
  if (search) {
    var params = search.split('&');
    params.forEach(function(item){
      var _item = item.split('=');
      urlParams[_item[0]] = decodeURIComponent(_item[1]);
    });
  }
  return urlParams;
  // sugarcane['urlParams']['hash'] = location.hash;
}

//唤醒客户端
sugarcane['openApp'] = function(params){
  var androidUrl = "https://static.jingjiribao.cn/package/jingjiribao_v2.1.0.apk",
    iosUrl = "https://itunes.apple.com/cn/app/xin-hua-she-fa-bu/id1024873168?l=cn&mt=8",
    wxUrl = "http://a.app.qq.com/o/simple.jsp?pkgname=com.tianwen.jjrb",
    linkUrl = "http://d.jingjiribao.cn",
    id = params['id'],
    //newsId =  params['newsId'],
    docType = params['docType'];
  var userAgent = sugarcane['app']['ua'];
  // if (userAgent.indexOf('micromessenger') > -1) {
  //   var isWx = true;
  // } else {
  //   var isWx = false;
  // }
  if (sugarcane['app']['ua'].indexOf('iphone') > -1 || userAgent.indexOf('ipad') > -1 || userAgent.indexOf('ipod') > -1) {
    var start = userAgent.indexOf('os '),
      versions = + userAgent.substr(start + 3, 3).replace( '_', '.' );

    if (versions >= 9) {
      window.location.href = linkUrl + "?id=" + id + '&docType='+docType;
    } else if (sugarcane['app']['isWeixin']) {
      window.location.href = wxUrl;
    } else {
      window.location.href = linkUrl + "?id=" + id + '&docType='+docType;
      setTimeout(function(){
        window.location.href = iosUrl;
      }, 3000);
    }
  } else {
    if (sugarcane['app']['isWeixin']) {
      window.location.href = wxUrl;
    } else {
      if(id){
        window.location.href = "jjrb://news?id=" + id+'&docType='+docType;
      }else{
        window.location.href = "jjrb://index";
      }
      setTimeout(function(){
        window.location.href = linkUrl;
      }, 3000);
    }
  }

}

/*
{title: "老区“红”变生态“绿”——革命老区六安脱贫攻坚见闻", desc: "分享来自经济日报客户端，更多精彩请下载http://d.jingjiribao.cn/index.html", link: "https://devapi.jingjiribao.cn/detail.html?id=112268", imgUrl: "https://static-jjrb.xinhuaapp.com/2018/10/23/20181023111021_4319.jpg@480w_360h_4e_1c_80Q_1x_255-255-255bgc.jpg"}
*/

/*
wx.ready(function () {
  var shareData = {
    title: "革命老区六安脱贫攻坚见闻",
    desc: "分享来自经济日报客户端，更多精彩请下载http://d.jingjiribao.cn/index.html",
    link: "https://testapi.jingjiribao.cn/detail.html?id=112268",
    imgUrl: "https://static-jjrb.xinhuaapp.com/2018/10/23/20181023111021_4319.jpg@480w_360h_4e_1c_80Q_1x_255-255-255bgc.jpg"
  };
  wx.onMenuShareAppMessage(shareData);
  wx.onMenuShareQQ(shareData);
  wx.onMenuShareQZone(shareData);
  wx.onMenuShareTimeline(shareData);
  // wx.updateAppMessageShareData(shareData);
  // wx.updateTimelineShareData(shareData);
});
*/



//二次分享
sugarcane['twoShare'] = function (param){
  var title = param.title,
      desc = param.desc,
      link = param.link,
      imgUrl = param.imgUrl,
      success = param.success,
      cancel = param.cancel,
      _id = param.id,
      _docType = param.docType;
  var data =  [{
      "time": + new Date(),
      "app_id" : "104", //经济日报应用id
      "event": "browser_access",
      "properties" : {
        "news_id" : _id,
        "doc_type": _docType
      }
    }];
  // if(sugarcane['app']['isShare']){
  //    $.ajax({
  //     "type":  "post",
  //     // "url": "https://flume.jingjiribao.cn",//生产
  //     "url": "https://testdata.xinhuaapp.com/flume/test",//测试
  //     "data": JSON.stringify(data)
  //   });
  // } 
 
  if(sugarcane['app']['isWeixin']){
    if(!link || link.length == 0){
      link = window.location.href;
    }

    wx.ready(function () {
      var shareData = {
        title: title,
        desc: desc,
        link: document.URL,
        imgUrl: imgUrl,
        cancel: function () {
          if(cancel){
            cancel();
          }
        },
        success:function(){
          if(success){
            success();
          }else{
            var data =  [{
              "time": + new Date(),
              "app_id" : "104", //经济日报应用id
              "event": "secondary_share",
              "properties" : {
                "news_id" : _id,
                "doc_type": _docType
              }
            }];
            // $.ajax({
            //   "type":  "post",
            //   // "url": "https://flume.jingjiribao.cn",//生产
            //   "url": "https://testdata.xinhuaapp.com/flume/test",//测试
            //   "data": JSON.stringify(data)
            // });
          }
        }
      };
      wx.onMenuShareAppMessage(shareData);
      wx.onMenuShareQQ(shareData);
      wx.onMenuShareQZone(shareData);
      wx.onMenuShareTimeline(shareData);
      // wx.updateAppMessageShareData(shareData);
      // wx.updateTimelineShareData(shareData);
    });

    wx.error(function (res) {
      console.log(res.errMsg);
    });
  }else if (sugarcane['app']['isQQ']) {
    var shareData = {
      title: title,
      summary: desc,
      url: document.URL,
      pic: imgUrl
    };
    setShareInfo(shareData);
  }
}

//分享页banner (不包括投票的banner)
sugarcane['shareBanner'] = function (params) {
  var _id = params.id, _docType = params.docType, _pageScreen = params.containObj;
  if(sugarcane['app']['isShare'] && !_pageScreen.find('.app-banner').length ){
    sugarcane.module.load('banner', function(listitemFn){
      var bannerObj = listitemFn({'id': _id, 'docType': _docType});
      _pageScreen.append(bannerObj);
      var _height = $(bannerObj).css('height');
      _pageScreen.css('margin-bottom',_height);
    });
  }
}

// 请求接口
sugarcane['ajaxApi'] = function(param) {
  var url = param['url'] || '';
  if (url) {
    // url = url;
    url = '/server' + url;
  } else {
    return false;
  }
  var data = param['data'] || {},
    successCallback = param['success'] || param['callback'];
  $.ajax({
    "type": param['type'] || "POST",
    "dataType": "json",
    "contentType": "application/json",
    "headers": {
      "token": sugarcane['app']['token']
    },
    "url": url,
    "data": JSON.stringify(data),
    "success": function(res){
      if (successCallback) successCallback(res);
    },
    "error": function(error){
      // peach.alert('error');
    }
  });
};

// 模块或页面读取
sugarcane.module = {};
sugarcane.module['state'] = {}; // 模块状态
sugarcane.module['callbackList'] = {}; // 模块回调等待队列，模块还没加载完时，等待回调的都在这排队
sugarcane.module['callback'] = function (moduleName) {
  // 模块加载好后，一一执行等待的回调队列
  if (sugarcane.module['callbackList'][moduleName] && sugarcane.module['callbackList'][moduleName].length) {
    var _callback = sugarcane.module['callbackList'][moduleName].shift();
    _callback(sugarcane.module[moduleName]);
    sugarcane.module.callback(moduleName);
  }
};
sugarcane.module['load'] = function (moduleName, callback) {
  // 模块配置
  var _moduleConfig = sugarcane.module['config'][moduleName];
  if (!_moduleConfig) {
    // 无配置项，就从page里找
    _moduleConfig = {
      'src': '/page/'+moduleName+'.js',
      'timestamp': sugarcane['version']
    };
  }

  // 存储callback
  if (!sugarcane.module['callbackList'][moduleName]) {
    sugarcane.module['callbackList'][moduleName] = [];
  }
  if (callback) sugarcane.module['callbackList'][moduleName].push(callback);
  // 模块状态
  var _state = sugarcane.module['state'][moduleName];
  if (_state == 'load' || sugarcane.module[moduleName]) {
    if (_state != 'load') sugarcane.module['state'][moduleName] = 'load';
    // 如果已经存在，直接回调
    sugarcane.module.callback(moduleName);
  } else if (_state == 'wait') {
    // 正在加载
    // 静静等着就好
    return false;
  } else {
    // 查看是否有依赖模块
    if (_moduleConfig['require']) {
      if (typeof(_moduleConfig['require']) == 'string') {
        var _require = [_moduleConfig['require']];
      } else {
        var _require = _moduleConfig['require'];
      }
    } else {
      var _require = [];
    }
    var _requireModule = null;
    if (_require.length > 0) {
      for (var i=0; i<_require.length; i++) {
        if (sugarcane.module['state'][_require[i]] != 'load') {
          _requireModule = _require[i];
          break;
        }
      }
    }
    if (_requireModule) {
      // 需要先加载依赖
      sugarcane.module.load(_requireModule, function(){
        sugarcane.module.load(moduleName);
      });
    } else {
      // 无依赖或依赖都已加载
      sugarcane.module['state'][moduleName] = 'wait';
      var _moduleSrc = _moduleConfig['src'];
      if (_moduleConfig['timestamp']) _moduleSrc += '?_t=' + _moduleConfig['timestamp'];
      var scriptObj = document.createElement('script');
      scriptObj.src = _moduleSrc;
      document.body.appendChild(scriptObj);
    }
    /* 目前使用 方案
      sugarcane.module['state'][moduleName] = 'load';
      sugarcane.module.callback(moduleName);
    */
  }
};

sugarcane.module['config'] = {
  'listitem': {
    'src': '/module/listitem.js',
    'timestamp': sugarcane['version']
  },
  'question': {
    'src': '/module/question.js',
    'timestamp': sugarcane['version']
  },
  'banner': {
    'src': '/module/banner.js',
    'timestamp': sugarcane['version']
  }
};

// 页面路由
sugarcane['timeboss'] = [];
sugarcane['route'] = {};
sugarcane.route['config'] = {}; // path、moduleName
sugarcane.route['status'] = null; // 记录history是否push了新页面地址
sugarcane.route['load'] = function(){
  $(window).scrollTop(0);
  // 清除模块内的定时器
  sugarcane['timeboss'].forEach(function(item){
    if(item.type == 'setTimeout'){
      clearTimeout(item.time);
    } else if (item.type == 'setInterval'){
      clearInterval(item.time);
    }
    item.time = null;
  });
  sugarcane['timeboss'] = [];
  // 清除所有模块的回调，避免页面逻辑混乱
  sugarcane.module['callbackList'] = {};
  // 根据路由加载并运行模块
  var _pathname = location.pathname;
  if (_pathname == '/') _pathname = '/index.html';
  var _moduleName = _pathname.replace(/\/(app\/)?(.*?)\.html/i, '$2');
  if (_moduleName) {
    sugarcane.module.load(_moduleName, function(moduleFn){
      moduleFn();
    });
  } else {
    console.log('未找到 '+_pathname+' 对应的模块');
  }
};
sugarcane.route['location'] = function(params){
  if (sugarcane['app']['isShare'] && history.pushState) {
    // state、title、href
    var _title = params['title'] || null;
    history.pushState(null, _title, params['href']);
    sugarcane.route.load();
  } else {
    location.href = params['href'];
  }
};
window.addEventListener('popstate', function(e) {
  sugarcane.route.load();
});

// 页面加载完之后才能调用
$(function(){
  // 获取appInfo
  if (!sugarcane['app']['isShare']) {
    peach.getAppInfo(function(appInfo){
      if (appInfo) {
        if (appInfo['userId']) sugarcane['app']['userId'] = appInfo['userId'];
        if (appInfo['token']) sugarcane['app']['token'] = appInfo['token'];
      }
      sugarcane.route.load();
    });
  } else {
    // 微信分享
    if(sugarcane['app']['isWeixin']){
      sugarcane.ajaxApi({
        'url': '/weixin/share',
        'data': {
          'url': location.href
        },
        "callback": function(res){
          if(res.code == 0){
            // res.data.debug = true;
            res.data.jsApiList =[
              'onMenuShareTimeline',
              'onMenuShareAppMessage',
              'onMenuShareQQ',
              'onMenuShareQZone',
              // 'updateAppMessageShareData',
              // 'updateTimelineShareData',
            ];
            wx.config(res.data);
          }
        }
      });
    }

    sugarcane.route.load();

  }
});

